﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace DWF.Studio.Plugin.Contract.Exceptions
{
    /// <summary>
    /// 插件异常
    /// </summary>
    [Serializable]
    public class PluginException : Exception, ISerializable
    {
        private string _exString = null;
        private string _exStackTrace = null;

        protected PluginException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            this._exString = info.GetString("_exString");
            this._exStackTrace = info.GetString("_exStackTrace");
            this.ExceptionType = info.GetString("ExceptionType");
            this.InnerException = (PluginException)info.GetValue("NewInnerException", this.GetType());
        }

        public PluginException(Exception ex)
            : base(ex.Message)
        {
            this._exString = ex.ToString();
            this._exStackTrace = ex.StackTrace;
            this.ExceptionType = ex.GetType().ToString();
            this.Source = ex.Source;

            this.InnerException = null;
            PluginException pex = this;
            Exception exp = ex;
            while (exp.InnerException != null)
            {
                pex.InnerException = new PluginException(ex.InnerException);
                pex = pex.InnerException;
                exp = exp.InnerException;
            }
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            info.AddValue("_exString", _exString);
            info.AddValue("_exStackTrace", _exStackTrace);
            info.AddValue("ExceptionType", this.ExceptionType);
            info.AddValue("NewInnerException", this.InnerException);
        }

        /// <summary>
        /// 异常类型
        /// </summary>
        public string ExceptionType
        {
            get;
            private set;
        }

        /// <summary>
        /// 内部异常
        /// </summary>
        public new PluginException InnerException
        {
            get;
            private set;
        }

        /// <summary>
        /// 堆追踪
        /// </summary>
        public override string StackTrace
        {
            get
            {
                return this._exStackTrace;
            }
        }

        public override System.Collections.IDictionary Data
        {
            get
            {
                return null;
            }
        }

        public override string ToString()
        {
            return this._exString;
        }
    }
}
